import { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import style from "./style.module.css";
import FavItem from "../../components/FavItem";
import * as api from "../../services/user.services";
import { IFav } from "./../../types";
import IconFont from "../../assets/icon";

export default function Fav() {
  const history = useHistory();
  const [items, setItems] = useState<IFav[]>([]);
  const [size, setSize] = useState<number>(5);
  // 更新职位数据
  useEffect(() => {
    const getData = async () => {
      let result = await api.listFav();
      setItems(result.items);
    };
    getData();
  }, []);

  const getData = async () => {
    let result = await api.listFav();
    if (result.stat === "OK") {
      setItems(result.items);
    } else {
      history.push("/");
    }
  };

  /**
   * 删除收藏职位功能
   * 1.获取ids
   * 2.调用相应api
   */
  const doRemove = async (id: string) => {
    await api.removeFav(id);
    getData();
  };

  //html部分
  if (items.length === 0) {
    return (
      <div className={style.back}>
        <div className={style.head}>
          <IconFont
            className={style.icon1}
            type="icon-houtui"
            onClick={history.goBack}
          />
          <div className={style.title}>
            <p className={style.text}>我的收藏</p>
          </div>
        </div>
        <div className={style.empty}>
          <IconFont className={style.icon2} type="icon-shoucang1" />
          <span>收藏是空的</span>
        </div>
      </div>
    );
  } else {
    return (
      <div className={style.back}>
        <div className={style.head}>
          <IconFont
            className={style.icon1}
            type="icon-houtui"
            onClick={history.goBack}
          />
          <div className={style.title}>
            <p className={style.text}>我的收藏</p>
          </div>
        </div>
        <div className={style.wrapper}>
          {items.map((item, index) => {
            if (index < size) {
              return (
                <FavItem
                  recruit={item}
                  key={index}
                  remove={() => doRemove(item.items[0]._id)}
                />
              );
            } else {
              return null;
            }
          })}
          <div className={style.complete} onClick={() => setSize(size + 5)}>
            {size >= items.length ? "没有更多了" : "加载更多"}
          </div>
        </div>
        <div className={style.control}></div>
      </div>
    );
  }
}
